<?php
namespace App\Http\Controllers\Admin;

use App\Services\WxCard\Factory\WxCardMemberCard;
use App\Services\WxCardMemberLevel\WxCardMemberLevelService;
use Illuminate\Http\Request;
use App\Services\WxCard\WxCardService;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 微信卡券--会员列表数据
 * @package App\Http\Controllers\Admin
 */
class WxCardMemberListController extends BaseWxController
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * 会员列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request, WxCardMemberCard $wxCardMemberCardSer)
    {
        //当前选择微信应用数据
        $curWxMp = \Auth::user()->getWxMpCurrent();
        $appid = $curWxMp ? $curWxMp['appid'] : '';
        if ($request->ajax()) {
            $pageSize = $request->get('pageSize', 10);
            $query = \App\Models\WxCardMemberList::with(['card','user','receive'])->select('*');
            $query->where('appid', $appid);
            //关键字搜索
            $keyword = $request->get('keyword', '');
            if ($keyword) {
                $query->where(function($query) use ($keyword) {
                    $query->where('nickname', 'like', '%' . $keyword . '%')->orWhere('user_info', 'like', '%' . $keyword . '%');
                });
//                $query->where('nickname', 'like', '%' . $keyword . '%');
            }
            $openid = $request->get('openid', '');
            if ($openid) {
                $query->where('openid', $openid);
            }
            $unionid = $request->get('unionid', '');
            if ($unionid) {
                $query->whereHas('user', function($query) use($unionid) {
                    $query->where('unionid', $unionid);
                });
            }
            //是否被激活
            $hasActive = $request->get('has_active', '');
            if (in_array($hasActive, ['0', '1'])) {
                $query->where('has_active', $hasActive);
            }
            //所属会员卡模型关联
            $cardBaseId = $request->get('card_base_id', 0);
            if ($cardBaseId) {
                $query->where('card_base_id', $cardBaseId);
            }
            //会员卡等级
            $levelId = $request->get('level_id', 0);
            if (!empty($levelId)){
                $query->where('level_id', $levelId);
            }
            //来源标识
            $outerStr = $request->get('outer_str', '');
            if (isset($outerStr)) {
                $query->whereHas('receive', function($query) use($outerStr) {
                    $query->where('outer_str', 'like', '%' . $outerStr . '%');
                });
            }
            //开始结束时间
            $startTime = $request->get('start_time', '');
            $endTime = $request->get('end_time', '');
            if (!empty($startTime) && !empty($endTime)) {
                $query->whereBetween('created_at', [$startTime, $endTime]);
            } elseif (!empty($startTime) && empty($endTime)) {
                $query->whereRaw("created_at >= '" . date('Y-m-d H:i:s', strtotime($startTime)) . "'");
            } elseif (empty($startTime) && !empty($endTime)) {
                $query->whereRaw("created_at <= '" . date('Y-m-d H:i:s', strtotime($endTime)) . "'");
            }
            $data = $query->orderBy('id', 'DESC')->paginate($pageSize)->toArray();
            if ($data['data']) {
                $cardList = $data['data'];
                foreach ($cardList as $k => $v) {
                    $v['user_card_status_str'] = $wxCardMemberCardSer->getStatus($v['user_card_status']);
                    $v['user_info'] = $wxCardMemberCardSer->fomatUserInfo($v['user_info']);
                    $v['card'] = $v['card'] ? $v['card'] : [];
                    $v['user'] = $v['user'] ? $v['user'] : [];
                    $cardList[$k] = $v;
                }
                $data['data'] = $cardList;
            }

            return $data;
        }
        //卡券列表
        $this->viewData['memberCardList'] = (new WxCardService($appid))->getCardListByType(WxCardService::CARD_TYPE_MEMBER_CARD);
        $this->viewData['memberLevelGroupList'] = (new WxCardMemberLevelService($appid))->getGroupCacheList();

        return view('admin.wxcardmemberlist.index', $this->viewData);
    }

    /**
     * 刷新用户会员卡数据
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\Http\Response|\Illuminate\View\View
     */
    public function upuser(Request $request)
    {
        if ($request->ajax()) {
            try{
                $cardId = $request->get('cardId', '');
                $userCode = $request->get('userCode', '');
                if (empty($cardId)){
                    throw new \Exception('会员卡卡号不能为空');
                }
                if (empty($userCode)){
                    throw new \Exception('用户code序列号不能为空');
                }
                $wxCardService = new WxCardService();
                $wxCardService->createCardObj(WxCardService::CARD_TYPE_MEMBER_CARD)->upsetUserinfo($cardId, $userCode);

                return $this->showMsg('success', '刷新用户会员卡成功', [], 'admin.wxcardmemberlist.upuser');
            }catch (\Exception $e){
                return $this->showMsg('error', $e->getMessage());
            }
        }
        return view('admin.wxcardmemberlist.upuser', $this->viewData);
    }
    /**
     * 导出会员列表
     */
    public function export(Request $request, WxCardMemberCard $wxCardMemberCardSer)
    {
        ini_set('memory_limit','3072M');// 临时设置最大内存占用为3G
        set_time_limit(0);//设置脚本最大执行时间 为0 永不过期

        $query = \App\Models\WxCardMemberList::with(['card','user','receive'])->select('*');
        //当前选择微信应用数据
        $curWxMp = \Auth::user()->getWxMpCurrent();
        $appid = $curWxMp ? $curWxMp['appid'] : '';
        $query->where('appid', $appid);
        //关键字搜索
        $keyword = $request->get('keyword', '');
        if ($keyword) {
            $query->where(function($query) use ($keyword) {
                $query->where('nickname', 'like', '%' . $keyword . '%')->orWhere('user_info', 'like', '%' . $keyword . '%');
            });
//                $query->where('nickname', 'like', '%' . $keyword . '%');
        }
        $openid = $request->get('openid', '');
        if ($openid) {
            $query->where('openid', $openid);
        }
        $unionid = $request->get('unionid', '');
        if ($unionid) {
            $query->whereHas('user', function($query) use($unionid) {
                $query->where('unionid', $unionid);
            });
        }
        //是否被激活
        $hasActive = $request->get('has_active', '');
        if (in_array($hasActive, ['0', '1'])) {
            $query->where('has_active', $hasActive);
        }
        //所属会员卡模型关联
        $cardBaseId = $request->get('card_base_id', 0);
        if ($cardBaseId) {
            $query->where('card_base_id', $cardBaseId);
        }
        //会员卡等级
        $levelId = $request->get('level_id', 0);
        if (!empty($levelId)){
            $query->where('level_id', $levelId);
        }
        //来源标识
        $outerStr = $request->get('outer_str', '');
        if (isset($outerStr)) {
            $query->whereHas('receive', function($query) use($outerStr) {
                $query->where('outer_str', 'like', '%' . $outerStr . '%');
            });
        }
        //开始结束时间
        $startTime = $request->get('start_time', '');
        $endTime = $request->get('end_time', '');
        if (!empty($startTime) && !empty($endTime)) {
            $query->whereBetween('created_at', [$startTime, $endTime]);
        } elseif (!empty($startTime) && empty($endTime)) {
            $query->whereRaw("created_at >= '" . date('Y-m-d H:i:s', strtotime($startTime)) . "'");
        } elseif (empty($startTime) && !empty($endTime)) {
            $query->whereRaw("created_at <= '" . date('Y-m-d H:i:s', strtotime($endTime)) . "'");
        }
        $query->orderBy('id', 'DESC');

        Excel::create("会员列表-" . date('Y-m-d'), function ($excel) use ($query, $wxCardMemberCardSer) {
            $excel->sheet('score', function ($sheet) use ($query, $wxCardMemberCardSer) {
                $sheet->row(1, ['openid', 'unionid', '用户昵称', '来源标识', '手机号', '会员等级','会员卡状态','积分','是否被激活', '领卡时间']);
                $query->chunk(2000, function ($arr) use ($sheet, $wxCardMemberCardSer) {
                    $data = [];
                    foreach ($arr as $k => $v){
                        $v['user_card_status_str'] = $wxCardMemberCardSer->getStatus($v['user_card_status']);
                        $v['user_info'] = $wxCardMemberCardSer->fomatUserInfo($v['user_info']);
                        $data[] = [
                            ($v['openid'] ? $v['openid'] : '-'),
                            ($v['user']['unionid'] ? $v['user']['unionid'] : '-'),
                            ($v['nickname'] ? $v['nickname'] : '-'),
                            ($v['receive']['outer_str'] ? $v['receive']['outer_str'] : '-'),
                            ($v['user_info'] ? ($v['user_info']['mobile'] ?? '-') : '-'),
                            ($v['level_name'] ? $v['level_name'] : '-'),
                            ($v['user_card_status_str'] ? $v['user_card_status_str'] : '-'),
                            ($v['bonus'] ? $v['bonus'] : '-'),
                            ($v['has_active'] == 1 ? '已激活' : '未激活'),
                            ($v['created_at'] ? $v['created_at'] : '-')
                        ];
                    }
                    $sheet->rows($data);
                });
            });
        })->export('xlsx');
    }

    /**
     * 会员统计
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function count(Request $request, WxCardMemberCard $wxCardMemberCardSer)
    {
        //当前选择微信应用数据
        $curWxMp = \Auth::user()->getWxMpCurrent();
        $appid = $curWxMp ? $curWxMp['appid'] : '';
        if ($request->ajax()) {
            $data = [];
            $cardBaseId = $request->card_base_id ?? 0;
            $startTime = $request->start_time ?? '';
            $endTime = $request->end_time ?? '';
            if ($cardBaseId){
                $levelList = (new WxCardMemberLevelService($appid))->getList($cardBaseId);
                if (!empty($levelList)){
                    $todayStartTime = date('Y-m-d').' 00:00:00';
                    $todayEndTime = date('Y-m-d') .' 23:59:59';
                    //日新增统计数
                    foreach ($levelList as $v){
                        $data[] = [
                            'name' => '日新增'. $v['name'] .'数',
                            'count' => $wxCardMemberCardSer->getCount(['cardBaseId'=>$cardBaseId,'levelId'=>$v['id'],'startTime'=>$todayStartTime,'endTime'=>$todayEndTime]),
                        ];
                    }
                    //累计新增数
                    foreach ($levelList as $v){
                        $data[] = [
                            'name' => '累计新增'. $v['name'] .'数',
                            'count' => $wxCardMemberCardSer->getCount(['cardBaseId'=>$cardBaseId,'levelId'=>$v['id']]),
                        ];
                    }
                }
                if (!empty($startTime) && !empty($endTime)){
                    //时间段内查询新增会员数
                    foreach ($levelList as $v){
                        $data[] = [
                            'name' => '新增'. $v['name'] .'数',
                            'count' => $wxCardMemberCardSer->getCount(['cardBaseId'=>$cardBaseId,'levelId'=>$v['id'],'startTime'=>$startTime,'endTime'=>$endTime]),
                        ];
                    }
                }
            }
            return $this->showMsg('success', '获取统计数据成功', $data, 'admin.wxcardmemberlist.count');
        }
        //卡券列表
        $this->viewData['memberCardList'] = (new WxCardService($appid))->getCardListByType(WxCardService::CARD_TYPE_MEMBER_CARD);

        return view('admin.wxcardmemberlist.count', $this->viewData);
    }
}
